<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author:陈红利
 * Date: 2017-5-10
 */

namespace app\home\logic;
use think\Model;
use think\db;
/**
 * 微信公众号接口类
 * Class WechatLogic
 * @package Home\Logic
 */
class WechatLogic extends Model
{
	public $weixin_config=array();
	public $dltoken;

	public function set_config($weixin_config) {
		$this->weixin_config= $weixin_config; //获取当前商户微信配置
	}
	/**
	 * [getOpenId 获取用户OPENID]
	 * @return [type] [description]
	 */
	public function ceshi() {
		return $this->weixin_config['appid'];
	}
	public function getOpenId () {
		
	    if (!isset($_GET['code'])) {
	    	$baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
	        //如果没有收到CODE返回值，就发送请求
	        $url = $this->PingUrl($baseUrl);
	        header("location:$url");
	        exit;
	    }else{
	    	
	        $code = $_GET['code'];
	        $openid = $this->caretFrom($code);
	        return $openid;
	    }
	}
	public function Getcode_two($wxconfigarr){

	        if(!isset($_GET['code'])){
	        	$this->set_config($wxconfigarr[0]);
	             $baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);

		        //如果没有收到CODE返回值，就发送请求
		$url = $this->PingUrl($baseUrl);

	            Header("Location: $url"); // 跳转到微信授权页面 需要用户确认登录的页面

	            exit();

	        }else{
	        	
	            if(!isset($_GET['code_count'])){

	                $this->set_config($wxconfigarr[0]);
	                $openids[]=$this->caretFrom($_GET['code']);
	                $_SESSION['openids']=$openids;
	                $this->set_config($wxconfigarr[1]);
	                $baseurl='http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
	                $baseurl=$this->add_querystring_var($baseurl,'code_count',1);
	                $baseUrl = urlencode($baseurl);
	    
		    $url = $this->PingUrl($baseUrl);

	                 Header("Location: $url"); // 跳转到微信授权页面 需要用户确认登录的页面

	                exit();

	            }elseif($_GET['code_count']==1){
	                $this->set_config($wxconfigarr[1]);
	                $openids=$_SESSION['openids'];
	                $openids[]=$this->caretFrom($_GET['code']);
	                $_SESSION['openids']=$openids;

	            }

	       
	        }

	}

	//向URL中添加参数
	private function add_querystring_var($url, $key, $value) {
	 $url=preg_replace('/(.*)(?|&)'.$key.'=[^&]+?(&)(.*)/i','$1$2$4',$url.'&');
	 $url=substr($url,0,-1);
	 if(strpos($url,'?') === false){
	  return ($url.'?'.$key.'='.$value);
	 } else {
	  return ($url.'&'.$key.'='.$value);
	 }
	}

	// 网页授权登录获取 鼎联OpendId

	public function GetOpenid_two($wxconfigarr)

	{

	    //通过code获得openid
	    if(is_array($_SESSION['code'])){
	        $key=0;
	    /* foreach ($_SESSION['code'] as $key => $value) {
	        	   $this->set_config($wxconfigarr[$key]);
	                $openids[] = $this->caretFrom($value);//获取网页授权access_token和用户openid
	        }*/
	        $this->set_config($wxconfigarr[$key]);
	        $openid=$this->caretFrom($_SESSION['code'][$key]);
	        $openids[]=$openid;
	        if($openid){
	        	$key++;
	        	$this->set_config($wxconfigarr[$key]);
	        	//$openids[]=$this->caretFrom($_SESSION['code'][$key]);
	        	$openid=$this->caretFrom($_SESSION['code'][$key]);
	        }

	        $_SESSION['code']=null;
	        return $openids;
	    } 
	}




	
	/**
	 * [getUserInfo 获取用户信息]
	 * @param  string $openid [description]
	 * @return [array]         [description]
	 */
	public function getUserInfo ($openid = '') {
	    if ($openid == '') {
	        $openid = $this->getOpenId();
	    }
	    $url['access_token'] = $this->getToken();
	    $url['openid'] = $openid;
	    $url['lang'] = 'zh_CN';
	    $newurl = self::ToUrlParams($url);
	    $baseUrl = "https://api.weixin.qq.com/cgi-bin/user/info?".$newurl;
	    $data = httpRequest($baseUrl,'GET');
	    $data = json_decode($data,true);
	    if (!isset($data['errcode']) && $data['openid'] != '') {
	        return $data;
	    }else{
	        self::$userInfoError = 'ERRORCODE:'.$data['errcode'].',errmsg:'.$data['errmsg'];
	        return self::$userInfoError;
	    }
	}
	
	/**
	 * [getToken 获取access_token]
	 * @return [type] [description]
	 */
	private function getToken () {
	    if ($this->weixin_config['web_expires'] < time()) {
	        $access_token = $this->accessToken();
	    }else{
	        $access_token = $this->weixin_config['web_access_token'];
	    }
	    return $access_token;
	} 
	/**
	 * [accessToken 生成accountToken]
	 * @return [array] [返回 $access_token['access_token'] $access_token['expire_time']]
	 */
	public function accessToken () {
	    $url['grant_type'] = 'client_credential';
	    $url['appid'] = $this->weixin_config['appid'];
	    $url['secret'] = $this->weixin_config['appsecret'];
	    $newurl = self::ToUrlParams($url);
	    $baseUrl = 'https://api.weixin.qq.com/cgi-bin/token?'.$newurl;
	    $data = file_get_contents($baseUrl);
	    $data = json_decode($data,true);
	    if ($data['access_token'] != '') {
	        $access_tokens['web_access_token'] = $data['access_token'];
	        $access_tokens['web_expires'] = time() + 7000;
	        M('wx_user')->where(array('appid'=>$this->weixin_config['appid']))->save($access_tokens);
	        return $access_tokens['web_access_token'];
	    }else{
	        $access_error = "ERRORCODE:".$data['errcode'].',errmsg:'.$data['errmsg'];
	        return FALSE;
	    }
	}
	
	/**
	 * [PingUrl 重组URL]
	 * @param [string] $baseUrl [当前网址]
	 * return string  返回发送的跳转的网址
	 */
	private function PingUrl ($baseUrl) {
	    $url['appid'] = $this->weixin_config['appid'];
	    $url['redirect_uri'] = $baseUrl;
	    $url['response_type'] = 'code';
	    $url['scope'] = 'snsapi_base';     //snsapi_base 只获取用户openid  snsapi_userinfo 弹出授权窗口 可获取用户地区 性别 昵称等信息
	    $url['state'] = "STATE"."#wechat_redirect";
	    $newsUrl = self::ToUrlParams($url);
	    return "https://open.weixin.qq.com/connect/oauth2/authorize?".$newsUrl;
	}
	
	/**
	 * [caretFrom 重组获取用户ID所需的参数]
	 * @param  [string] $code [返回的code参数]
	 * @return [string]       [用户openid]
	 */
	private  function caretFrom ($code) {
	    $data['appid'] = $this->weixin_config['appid'];
	    $data['secret'] =$this->weixin_config['appsecret'];
	    $data['code'] = $code;
	    $data['grant_type'] = 'authorization_code';
	    $newString = $this->ToUrlParams($data);
	    return $this->SendFrom($newString);
	}
	/**
	 * [SendFrom 获取opnid]
	 * @param [string] $str [description]
	 */
	private function SendFrom ($str) {
	    $url = "https://api.weixin.qq.com/sns/oauth2/access_token?".$str;
	    $data = file_get_contents($url);
	    $data = json_decode($data,true);
	    return $data['openid'];
	}

	
	/**
	 * [ToUrlParams 重组url参数]
	 * @param [array] $data [需要重组的数组]
	 */
	protected static function ToUrlParams ($data) {
	     $url = "";
	     foreach ($data as $key => $value) {
	          $url .= $key . "=" .$value ."&";
	     }
	     $url = trim($url,"&");
	     return $url;
	}
}